package gift.justflower.ecp.controller;

import gift.justflower.ecp.bean.Goods;
import gift.justflower.ecp.bean.Sell;
import gift.justflower.ecp.bean.User;
import gift.justflower.ecp.util.DateUtil;
import gift.justflower.ecp.view.ChartView;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.At;

import java.sql.Timestamp;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 基本情况统计
 * author：AB
 * time：2018年7月17日 23:05:16
 */
@At("/chart")
@IocBean
@RequiresUser
public class ChartController {
    @Inject
    private Dao dao;

    @At
    public Object week() {
        User user = (User) Mvcs.getHttpSession().getAttribute("user");

        Date beginDayOFWeek = DateUtil.getBeginDayOfWeek();
        Timestamp endDayOfBegin = DateUtil.getDayEndTime(beginDayOFWeek);
        LocalDateTime startTime = DateUtil.getDateTimeOfTimestamp(beginDayOFWeek.getTime());
        LocalDateTime endTime = DateUtil.getDateTimeOfTimestamp(endDayOfBegin.getTime());

        ChartView chartView = new ChartView();
        String[] xDatas = new String[7];
        xDatas[0] = "周一";
        xDatas[1] = "周二";
        xDatas[2] = "周三";
        xDatas[3] = "周四";
        xDatas[4] = "周五";
        xDatas[5] = "周六";
        xDatas[6] = "周日";
        chartView.setxDatas(xDatas);

        Double[] inYDatas = new Double[7];
        for (int i = 0; i < 7; i++) {
            List<Sell> sells = dao.query(Sell.class, Cnd.where("userId", "=", user.getId()).and("createTime", ">=", startTime.plusDays(i)).and("createTime", "<=", endTime.plusDays(i)));
            dao.fetchLinks(sells,null);
            inYDatas[i] = sells.stream().mapToDouble(sell -> sell.getCount() * sell.getGoods().getOutPrice()).sum();
        }
        Double[] outYDatas = new Double[7];
        for (int i = 0; i < 7; i++) {
            List<Goods> goods = dao.query(Goods.class, Cnd.where("userId", "=", user.getId()).and("createTime", ">=", startTime.plusDays(i)).and("createTime", "<=", endTime.plusDays(i)));
            outYDatas[i] = goods.stream().mapToDouble(good -> good.getCount() * good.getOutPrice()).sum();
        }

        chartView.setyInDatas(inYDatas);
        chartView.setyOutDatas(outYDatas);
        return chartView;
    }

    public static void main(String[] args) {
        Date beginDayOFWeek = DateUtil.getBeginDayOfWeek();
        Timestamp endDayOfBegin = DateUtil.getDayEndTime(beginDayOFWeek);
        System.out.println(beginDayOFWeek);
        System.out.println(endDayOfBegin);
    }
}
